import { message, Modal } from "ant-design-vue";
import qs from "qs"; // 需要安装并引入 qs
import moment from "moment";
export default {
  data() {
    return {
      loading: false,
      dialogVisible: false,
      title: "",
      queryForm: {
        current: 20,
        offset: 1,
      },
      total: 0,
      tableData: [],
      type: "Create",
      id: null,
      currentRecord: null,
      exportLoading: false,
      submitLoading: false,
    };
  },

  methods: {
    moment,
    // 格式化请求参数
    formatRequestData(type, data) {
      // 默认格式
      switch (type) {
        case "formData":
          return qs.stringify(data);
        case "json":
          return {
            ...data,
          };
      }
    },

    // 获取列表
    getList() {
      const { method, url } = this.requestConfig.Get;
      if (!url) {
        console.error("请配置 getList 接口路径");
        return;
      }
      this.loading = true;
      this.$axios[method](url, {
        params: this.queryForm,
      })
        .then((res) => {
          this.loading = false;
          if (res.data.code === 0) {
            this.tableData = res.data.data.map((item) => {
              item["showPhone"] = false;
              return item;
            });
            this.total = res.data.total;
          } else {
            message.error(res.data.msg || "获取列表失败");
          }
        })
        .catch((err) => {
          this.loading = false;
          console.error("获取列表错误:", err);
          message.error("获取列表失败");
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 新增
    add() {
      this.dialogVisible = true;
      this.title = this.modalConfig.addTitle || "新增";
      this.id = null;
      this.form.resetFields();
      this.type = "Add";
    },

    // 编辑
    edit(record) {
      this.dialogVisible = true;
      this.type = "Edit";
      this.title = this.modalConfig.editTitle || "修改";
      this.id = record.id;
      this.currentRecord = record;
      const { method, url, type } = this.requestConfig.Detail;

      if (!url) {
        this.$nextTick(() => {
          const formData = this.formatFormData
            ? this.formatFormData(record)
            : record;
          this.form.setFieldsValue(formData);
        });
        return;
      }
      const params = this.formatRequestData(type, record);

      this.$axios
        .get(url, { params })
        .then((res) => {
          if (res.data.code === 0) {
            this.$nextTick(() => {
              const formData = this.formatFormData
                ? this.formatFormData(res.data.data)
                : res.data.data;
              this.form.setFieldsValue(formData);
            });
          } else {
            message.error(res.data.msg || "获取数据失败");
          }
        })
        .catch((err) => {
          console.error("获取详情错误:", err);
          message.error("获取数据失败");
        });
    },

    // 查看详情
    view(record) {
      this.dialogVisible = true;
      this.type = "View";
      this.title = this.modalConfig.viewTitle || "查看详情";
      this.id = record.id;
      this.currentRecord = record;
      const { method, url, type
      } = this.requestConfig.Detail;

      if (!url) {
        this.$nextTick(() => {
          const formData = this.formatFormData
            ? this.formatFormData(record)
            : record;
          this.form.setFieldsValue(formData);
        });
        return;
      }
      const params = this.formatRequestData(type, record);
      if (typeof record === 'string' || typeof record === 'number') {
        this.$axios[method](`${url}/${record}`)
          .then((res) => {
            if (res.data.code === 0) {
              this.$nextTick(() => {
                const formData = this.formatFormData
                  ? this.formatFormData(res.data.data)
                  : res.data.data;
                this.form.setFieldsValue(formData);
              });
            } else {
              message.error(res.data.msg || "获取数据失败");
            }
          })
          .catch((err) => {
            console.error("获取详情错误:", err);
            message.error("获取数据失败");
          });
      } else {
        this.$axios[method](url, { params })
          .then((res) => {
            if (res.data.code === 0) {
              this.$nextTick(() => {
                const formData = this.formatFormData
                  ? this.formatFormData(res.data.data)
                  : res.data.data;
                this.form.setFieldsValue(formData);
              });
            } else {
              message.error(res.data.msg || "获取数据失败");
            }
          })
          .catch((err) => {
            console.error("获取详情错误:", err);
            message.error("获取数据失败");
          });
      }

    },

    // 删除
    del(record) {
      this.type = "Del";
      const { method, url, type } = this.requestConfig[this.type];
      if (!url) {
        message.warning("请配置 delete 接口路径");
        return;
      }

      Modal.confirm({
        title: "确认删除",
        content:
          this.modalConfig.deleteConfirm ||
          "确定要删除该记录吗？删除后不可恢复！",
        okText: "确认",
        cancelText: "取消",
        onOk: () => {
          //格式化参数
          const data = this.formatRequestData(type, { id: record.id });
          if (method === "get") {
            this.$axios[method](url, { params: data })
              .then((res) => {
                if (res.data.code === 0) {
                  message.success("删除成功");
                  this.getList();
                } else {
                  // message.error(res.data.msg || '删除失败');
                }
              })
              .catch((err) => {
                console.error("删除错误:", err);
                message.error("删除失败");
              });
          } else {
            this.$axios[method](url, data)
              .then((res) => {
                if (res.data.code === 0) {
                  message.success("删除成功");
                  this.getList();
                } else {
                  // message.error(res.data.msg || '删除失败');
                }
              })
              .catch((err) => {
                console.error("删除错误:", err);
                message.error("删除失败");
              });
          }
        },
      });
    },

    // 提交表单
    handleSubmit(specialData) {
      if (this.type === "View") {
        this.dialogVisible = false;
        return;
      }
      const { method, url, type } = this.requestConfig[this.type];
      if (!url) {
        message.warning("请配置 add/update 接口路径");
        return;
      }
      this.form.validateFields((err, values) => {
        if (err) return;

        // 构建完整的提交数据
        const submitData = {
          ...values,
          id: this.id,
          ...this.formatAddData(specialData),
        };
        //格式化参数
        const data = this.formatRequestData(type, submitData);
        this.submitLoading = true;
        if (method === "get") {
          this.$axios[method](url, { params: data })
            .then((res) => {
              if (res.data.code === 0) {
                message.success(`${this.type === "Add" ? "添加" : "修改"}成功`);
                this.dialogVisible = false;
                this.getList();
                this.form.resetFields();
              }
            })
            .finally(() => {
              this.submitLoading = false;
            })
            .catch((err) => {
              console.error("提交表单错误:", err);
              // message.error('操作失败');
            });
        } else {
          this.$axios[method](url, data)
            .then((res) => {
              if (res.data.code === 0) {
                message.success(`${this.type === "Add" ? "添加" : "修改"}成功`);
                this.dialogVisible = false;
                this.getList();
                this.form.resetFields();
              }
            })
            .finally(() => {
              this.submitLoading = false;
            })
            .catch((err) => {
              console.error("提交表单错误:", err);
              // message.error('操作失败');
            });
        }
      });
    },

    // 分页大小改变
    onShowSizeChange(current, pageSize) {
      this.queryForm.current = pageSize;
      this.getList();
    },

    // 页码改变
    pageChange(current) {
      this.queryForm.offset = current;
      this.getList();
    },

    // 清除查询条件
    cleanQuery() {
      this.queryForm = {
        current: 20,
        offset: 1,
      };
      this.getList();
    },
    // 改变状态
    changeStatus(record) {
      this.type = "Edit";
      const { method, url, type } = this.requestConfig[this.type];
      if (!url) {
        return;
      }
      const data = this.formatRequestData(type, record);
      this.$axios[method](url, data)
        .then((res) => {
          if (res.data.code === 0) {
            this.$message.success("状态改变成功");
            this.getList();
          }
        })
        .catch((err) => {
          console.error("改变状态错误:", err);
          this.$message.error("改变状态失败");
        });
    },
    // 导出
    async exportData(url, data, title) {
      try {
        // 设置按钮加载状态（假设有这个变量）
        this.btnLoading = true;
        // 使用axios发送请求并指定responseType为blob
        const response = await this.$axios({
          method: "post",
          url, // 根据实际baseURL调整
          data,
          responseType: "blob",
        });
        // 创建Blob对象
        const blob = new Blob([response.data], {
          type: "application/vnd.ms-excel",
        });

        // 创建下载链接
        const link = document.createElement("a");
        link.download = `${title}.xlsx`;
        link.style.display = "none";
        link.href = URL.createObjectURL(blob);

        // 添加到文档并触发点击
        document.body.appendChild(link);
        link.click();

        // 清理资源
        URL.revokeObjectURL(link.href);
        document.body.removeChild(link);
      } catch (error) {
        // 错误处理
        this.$message.error("导出失败：" + (error.message || "未知错误"));
        console.error("导出错误:", error);
      } finally {
        // 无论成功失败都重置按钮状态
        this.btnLoading = false;
      }
    }
  },
};
